<template>
  <el-card style="height: 100%">
    <!-- 1.面包屑 -->
    <MyBread url="student" level1="预约练车时间" />
    <el-empty
      description="教练暂未安排练车时间"
      v-if="!isCoachArranged"
    ></el-empty>
    <template v-else>
      <!-- 2.显示教练安排时间-->
      <h2>教练练车时间安排</h2>
      <el-form
        :model="timeArrangeByCoach"
        label-width="170px"
        label-position="right"
      >
        <el-form-item label="开始预约日期">
          <el-input v-model="timeArrangeByCoach.startDate" readonly></el-input>
        </el-form-item>
        <el-form-item label="结束预约日期">
          <el-input v-model="timeArrangeByCoach.endDate" readonly></el-input>
        </el-form-item>
        <el-form-item label="开始预约时间">
          <el-input v-model="timeArrangeByCoach.startTime" readonly></el-input>
        </el-form-item>
        <el-form-item label="结束预约时间">
          <el-input v-model="timeArrangeByCoach.endTime" readonly></el-input>
        </el-form-item>
        <el-form-item label="练车时长">
          <el-input
            v-model="timeArrangeByCoach.intervalTime"
            readonly
          ></el-input>
        </el-form-item>
        <el-form-item label="每个时间段最多人数">
          <el-input
            v-model="timeArrangeByCoach.TrainNumber"
            readonly
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 3.显示学员选择预约练车时间 -->
      <h2>学员练车时间预约</h2>
      <span class="el-form-item__label distance">预约日期选择</span>
      <el-date-picker
        v-model="selectedDate"
        type="date"
        placeholder="请选择日期"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        :picker-options="pickerOptions"
        @blur="verifyDate"
        :disabled="disableAppoint"
        class="width"
      ></el-date-picker>
      <span class="el-form-item__label distance">预约开始时间</span>
      <el-time-select
        v-model="selectTimeInterval"
        :picker-options="timePickerOptions"
        placeholder="请选择预约时间"
        class="width"
        @blur="verifyTime()"
        :disabled="disableAppoint"
      ></el-time-select>
      <div style="float: right">
        <el-button
          type="primary"
          @click="startAppointButton()"
          style="margin-top: 25px"
          plain
          round
          >开始预约</el-button
        >
        <el-button type="success" @click="submitAppointButton()" plain round
          >提交预约</el-button
        >
        <el-button type="danger" @click="deleteAppointButton()" plain round
          >删除预约</el-button
        >
      </div>
    </template>
  </el-card>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "AppointTrain",
  data() {
    return {
      selectedDate: "", // 预约日期
      selectTimeInterval: "", // 预约时间
      disableAppoint: true, // 控制预约日期与预约时间的禁用
      isCoachArranged: true, // 教练是否安排练车时间：true:是 / false:否
      // 预约日期选项
      pickerOptions: {
        // 只能预约今天之后的日期，不包括今天
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
        // 快捷选项
        shortcuts: [
          {
            text: "明天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "后天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 2);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      timePickerOptions: {}, // 预约时间选项
      timeArrangeByCoach: {}, // 教练练车时间安排
      currentStudentAppoint: null, // 学员预约信息
    };
  },
  methods: {
    // 验证所选日期是否超出教练安排时间
    verifyDate() {
      const appoint_date = new Date(this.selectedDate);
      const arrange_start_date = new Date(this.timeArrangeByCoach.startDate);
      const arrange_end_date = new Date(this.timeArrangeByCoach.endDate);
      if (
        appoint_date.getTime() < arrange_start_date.getTime() ||
        appoint_date.getTime() > arrange_end_date.getTime()
      ) {
        this.$message.info("所选日期不在教练安排日期范围内");
        this.selectedDate = "";
        return;
      }
    },
    // 验证选择的开始时间是否为结束时间
    verifyTime() {
      if (this.selectTimeInterval === this.timeArrangeByCoach.endTime) {
        this.$message.info("所选时间为结束时间，请重新选择");
        this.selectTimeInterval = "";
      }
    },
    // 开始预约 -- 权限检测 + 开启选项框的使用
    async startAppointButton() {
      // 权限验证
      if (
        !(await this.haveThisPermission(this.$route.path, "修改学员预约时间"))
      ) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      this.disableAppoint = false;
    },
    // 提交预约
    async submitAppointButton() {
      if (!this.disableAppoint) {
        // 验证是否没有选择预约时间或预约日期
        if (this.selectTimeInterval === "" || this.selectedDate === "") {
          this.$message.warning("请选择预约日期或预约时间");
          return;
        }
        if (this.currentStudentAppoint === null) {
          // 第一次预约
          // 封装学员预约数据
          let studentAppoint = {
            coachID: this.currentStudentInfo.coachID,
            identify: this.currentStudentInfo.identify,
            studentName: this.currentStudentInfo.name,
            selectedDate: this.selectedDate,
            selectTimeInterval: this.selectTimeInterval,
            isSure: false,
            submitTime: new Date().toLocaleString(),
            confirmTime: "",
          };
          // 保存数据
          await this.$https.addUserData("/studentAppoint", studentAppoint);
          this.disableAppoint = true;
          this.$message.success("已提交预约");
          // 重新获取预约数据
          this.getStudentAppoint();
        } else {
          // 第N次预约
          // 判断在预约时间还没有过去时 教练是否确认预约
          if (this.currentStudentAppoint.isSure) {
            this.$message.info("教练已确认预约，不可再次预约");
            this.getStudentAppoint();
            this.disableAppoint = true;
          } else {
            this.currentStudentAppoint.selectedDate = this.selectedDate;
            this.currentStudentAppoint.selectTimeInterval =
              this.selectTimeInterval;
            this.currentStudentAppoint.submitTime = new Date().toLocaleString();
            await this.$https.updateUserData(
              "/studentAppoint",
              this.currentStudentAppoint.id,
              this.currentStudentAppoint
            );
            this.disableAppoint = true;
            this.$message.success("已提交预约");
          }
        }
      } else {
        this.$message.info("请选择开始预约按钮进行预约操作");
      }
    },
    // 删除预约
    async deleteAppointButton() {
      // 权限验证
      if (
        !(await this.haveThisPermission(this.$route.path, "删除学员预约时间"))
      ) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      // 数据处理
      if (this.currentStudentAppoint === null) {
        this.$message.info("目前没有预约");
      } else {
        // 可以删除预约的前提是教练未确认预约
        if (this.currentStudentAppoint.isSure) {
          this.$message.info("教练已确认预约，不可删除预约");
        } else {
          this.$confirm("是否删除预约?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "danger",
          })
            .then(async () => {
              // 清空数据
              this.selectedDate = "";
              this.selectTimeInterval = "";
              this.disableAppoint = true;
              // 删除数据库数据
              await this.$https.deleteUserData(
                "/studentAppoint",
                this.currentStudentAppoint.id
              );
              this.currentStudentAppoint = null;
              this.$message.success("已删除预约");
            })
            .catch(() => {
              this.$message.info("已取消删除");
            });
        }
      }
      this.disableAppoint = true;
    },
    // 获取学员预约数据
    async getStudentAppoint() {
      const { data } = await this.$https.getUserData({
        url: "/studentAppoint",
        identify: this.currentStudentInfo.identify,
      });
      this.currentStudentAppoint = data[0];
      this.selectedDate = this.currentStudentAppoint.selectedDate;
      this.selectTimeInterval = this.currentStudentAppoint.selectTimeInterval;
    },
  },
  computed: {
    ...mapState("StudentModule", ["currentStudentInfo", "currentCoachInfo"]),
  },
  async mounted() {
    // 获取学员的信息
    await this.$store.dispatch("StudentModule/getCurrentStudentInfo");
    // 根据学员coachID获取教练信息
    await this.$store.dispatch(
      "StudentModule/getCoachIfoByCurrentStudentCoachID",
      this.currentStudentInfo.coachID
    );
    // 获取【学员预约信息】
    const { data: StudentAppoint } = await this.$https.getUserData({
      url: "/studentAppoint",
      identify: this.currentStudentInfo.identify,
    });
    if (StudentAppoint.length !== 0) {
      this.currentStudentAppoint = StudentAppoint[0];
      this.selectedDate = this.currentStudentAppoint.selectedDate;
      this.selectTimeInterval = this.currentStudentAppoint.selectTimeInterval;
      // 判断预约日期是否已经过去，若预约时间已过，则可以再次预约
      if (
        Date.now() > new Date(this.currentStudentAppoint.selectedDate).getTime()
      ) {
        this.currentStudentAppoint.isSure = false;
      }
    }
    // 根据教练identify获取【练车时间安排】
    const { data: CaochArrange } = await this.$https.getUserData({
      url: "/timeArrange",
      identify: this.currentCoachInfo.identify,
    });
    // 若数据为空 -- 即教练未安排练车时间
    if (CaochArrange.length === 0) {
      this.isCoachArranged = false;
      return;
    }
    this.timeArrangeByCoach = CaochArrange[0];
    this.timePickerOptions = {
      start: CaochArrange[0].startTime,
      end: CaochArrange[0].endTime,
      step: CaochArrange[0].intervalTime,
    };
  },
};
</script>

<style scoped>
.width {
  width: 100%;
  margin-left: 15px;
}
.distance {
  margin-left: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
}
h2 {
  font-weight: 900;
  font-family: "Courier New", Courier, monospace;
  margin-top: 30px;
}
</style>